<template>
    <div class="verifyPage" >
        <!-- 手机/邮箱图片验证码发送 -->
        <div class="verify-container" v-if="showCodePage==2">
            <div class="inputBox">
                <input class="phoneNum verificationInput"  name="" id=""  :placeholder="placeholderMsgPhone" v-model="phoneNum">
                <div class="codeInput">
                    <input class="verificationInput" type='text' name="" id="" placeholder="图片验证码" v-model="imgCode">
                    <span class="codeImg" @click="getImgCode"><img :src="imgCodeUrl" alt=""></span>
                </div>
                <span class="errMsg" >{{errMsg}}</span>
                
            </div>
            <div class="sendPart">
                <div class="commonBtn sendPhone" @click="sendPhoneCode"> 
                    <span >
                    发&nbsp;&nbsp;送
                    </span>
                </div>
                <span class="changeSpan" @click="changeMode" v-if="bindEmailFlag !=1">{{changeMsg}}</span>
            </div>    
        </div>

        <!-- 手机或邮箱验证码发送 -->
        <div class="verify-send" v-if="showCodePage==1">
            <!-- 发送验证码 -->
            <div class="content" v-if="showEmail ==1">
                <span  class="text sendMsgTips">{{phoneMsg}}</span>
                <div class="codeInput">
                    <input class="verificationInput" type='text'  :placeholder="codeMsg" v-model="seccode">            
                    <input class="commonBtn repeateCodeBtn" type='button' value="重新获取" @click="reacquireCodeFun" v-if="attcode">
                    <input class="commonBtn grayBtn" type='button' :value="code_ts" v-else>

                    <span class="errMsg">{{errMsg}}</span>
                </div>
                <div class="inputSend">
                    <input class="sureBtn commonBtn" type='button' name="" id="" value="确 定"  @click="enterSuccess">
                </div>
                
            </div>
            <!-- 填写完成后的页面 -->
            <div class="content-success" v-if="showEmail == 2">
                <div v-if="renewFlag == 1">
                    <span  class="text">你已成功注册MEIO,是否绑定邮箱?</span>
                    <div class="codeInput">
                        <input class="sureBtn commonBtn active" type='button' name="" id="" value="确   定" @click="bindEmail">
                        <router-link to="/login"><input class="sureBtn commonBtn" type='button' name="" id="" value="跳   过" ></router-link>
                    </div>
                </div>
                
                <div v-if="renewFlag == 2">
                    <span  class="text">您已成功绑定邮箱，请重新登录账号</span>
                    <div class="codeInput" >
                    <router-link to="/login">
                        <input class="sureBtn commonBtn active" type='button' name="" id="" value="确   定">
                    </router-link>
                    
                    </div>
                </div>
            </div> 
        </div>
        <span class="backSpan" @click="backToIndex"><i class="el-icon-refresh-left"></i>返回首页</span>
    </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
    data(){
        return{
            placeholderMsgPhone:"输入手机号码", // 输入框提示信息
            changeMsg:"切换至邮箱验证",
            verifiType:1, // 手机或邮箱图片验证
            phoneMsg:"", // 
            codeMsg:"短信验证码",
            showCodePage:2, // 显示图片验证或短信验证模块
            phoneNum:"", // 手机号或邮箱
            enterFlag:1, // 是登陆的流程还是注册的流程
            showEmail:1, // 显示邮箱绑定流程
            renewFlag:1, // 显示邮箱绑定成功模块
            bindEmailFlag:2, // 绑定邮箱流程
            errMsg:"", // 错误信息
            sec:"60", // 倒计时秒数
            code_ts: '获取验证码', //倒计时提示文字
            attcode: false,  //点击获取验证码按钮判断
            seccode:"",
            timer:"", // 定时器
            imgCodeUrl:"",
            imgCode:"", // 图片验证码
            uuid:""
        }
    },
    created(){
        // 页面创建时 获取注册时传过来的手机号 根据是否含有手机号判断时登录还是注册
        this.phoneNum = this.$route.query.phoneNum?this.$route.query.phoneNum:""
        this.showPage()
        // 获取图片验证码
        this.initImgCode()
    },
    methods:{
        ...mapMutations(['changeLogin']),
        backToIndex(){
            this.$router.push('/index')
        },
        // 初始化图片验证码
        initImgCode(){
            // 页面初始化时得到uuid
            this.uuid = this.$common.guid()
            this.getImgCode()
        },
        // 获取图片验证码
        getImgCode(){
            var _this = this
            this.$api.getImgCode(this.uuid,{responseType: "arraybuffer"})
            .then(function (response) {
                //将从后台获取的图片流进行转换
                return 'data:image/png;base64,' + btoa(
                    new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
                );
            }).then(function (data) {
                //接收转换后的Base64图片
                _this.imgCodeUrl = data;
            }).catch(function (err) {})
        },
        // 显示不同界面
        showPage(){
            if(!this.phoneNum){// 登陆 或 绑定邮箱
                this.showCodePage = 2 // 显示发送图片验证码的界面
                this.enterFlag = 1
            }else{ // 注册
                this.showCodePage = 1
                this.enterFlag = 2
                let str = this.phoneNum.substr(0,3)+'****'+this.phoneNum.substr(7)
                this.codeMsg = "短信验证码"
                this.phoneMsg = `为了确保账号安全，已向手机${str}发送短信验证码`
                this.timeCountDown()
            }
        },
        changeMode(){ // 切换手机或邮箱验证
            this.phoneNum = ""
            if(this.verifiType == 1){
                this.placeholderMsgPhone = "输入邮箱"
                this.changeMsg = "切换至手机验证"
                this.verifiType = 2
            }else{
                this.placeholderMsgPhone = "输入手机号码"
                this.changeMsg = "切换至邮箱验证"
                this.verifiType = 1
            }
        },
        sendPhoneCode(){ // 手机或邮箱验证
            if(this.showEmail == 1){ // 登陆流程的验证码
                // 发送验证码
                const params = {
                    scode:this.imgCode,
                    uuid:this.uuid
                }
                if(this.verifiType == 1){
                    params.phone = this.phoneNum
                }else{
                    params.email = this.phoneNum
                }
                this.$api.loginSendCode({params:params})
                .then(result=>{
                    if(result.data.success){ // 成功后
                        this.showCodePage = 1
                        this.showEmail = 1
                        var str = this.phoneNum.substr(0,3)+'****'+this.phoneNum.substr(7)
                        this.timeCountDown()
                        if(this.verifiType == 1){ // 手机验证
                            this.codeMsg = "短信验证码"
                            this.phoneMsg = `验证码已发送至手机${str}`
                            
                        }else{ // 邮箱验证
                            this.codeMsg = "邮箱验证码"
                            this.phoneMsg = `验证码已发送至邮箱${str}`
                        }
                    }else{
                        this.$message({center: true,message: result.data.message?result.data.message:"网络错误,请稍后再试",type: 'warning'});
                    }
                })
                
            }else{
                // 发送邮箱验证码
                this.$api.registerSendECode({params:{email: this.phoneNum,scode:this.imgCode,uuid:this.uuid}})
                .then(result=>{
                    if(result.data.success){ // 成功后
                        this.showCodePage = 1
                        this.showEmail = 1
                        var str = this.phoneNum.substr(0,3)+'****'+this.phoneNum.substr(7)
                        this.timeCountDown()
                        this.codeMsg = "邮箱验证码"
                        this.phoneMsg = `验证码已发送至邮箱${str}`
                        this.seccode = ""
                    }else{
                        this.$message({center: true,message: result.data.message?result.data.message:"网络错误,请稍后再试",type: 'warning'});
                    }
                })
            }
        },
        enterSuccess(){ // 验证 验证码
            if(this.enterFlag == 1){// 手机号登陆
                const params = {
                    seccode: this.seccode,
                    uuid:this.uuid
                }
                if(this.verifiType == 1){
                    params.phone = this.phoneNum
                }else{
                    params.email = this.phoneNum
                }
                this.$api.testLoginCode({params:params})
                .then(result=>{
                    if(result.data.success){ // 成功后
                        // Toast("登陆成功")
                         this.$message({center: true,message: "登陆成功",type: 'success'});
                        localStorage.userInfo = JSON.stringify(result.data.data)
                        // 将用户token保存到vuex中
                        this.changeLogin({ token: result.data.token });
                        this.clearTimer()
                        this.$router.push('/backIndex')
                    }else{
                        this.$message({center: true,message: result.data.message?result.data.message:"网络错误,请稍后再试",type: 'warning'});
                    }
                })
            }else if(this.enterFlag == 2){ // 注册验证手机号
                if(this.bindEmailFlag == 1){ // 注册验证邮箱 验证码
                    // 验证邮箱验证码
                    const params = {
                        uuid:this.uuid,
                        email: this.phoneNum,
                        seccode:this.seccode,
                        phone:JSON.parse(sessionStorage.registerParams).phoneNum
                    }
                    this.$api.testRegisterECode(params)
                    .then(result=>{
                        if(result.data.success){ // 成功后
                            this.showEmail = 2
                            this.renewFlag = (this.bindEmailFlag == 1)? 2 :1
                            this.clearTimer()
                        }else{
                            this.$message({center: true,message: result.data.message?result.data.message:"网络错误,请稍后再试",type: 'warning'});
                        }
                    })
                }else{ // 注册验证手机号验证码
                    let params = JSON.parse(sessionStorage.registerParams)
                    params.seccode =this.seccode
                    params.phone = params.phoneNum
                    params.password = params.passwordNum
                    this.$api.testRegisterPCode(params).then(result=>{
                        if(result.data.success){ // 成功后
                            this.showEmail = 2
                            this.renewFlag = (this.bindEmailFlag == 1)? 2 :1
                            this.clearTimer()
                        }else{
                            this.$message({center: true,message: result.data.message?result.data.message:"网络错误,请稍后再试",type: 'warning'});
                        }
                    })
                }
            }
        },
        timeCountDown(){ // 时间倒计时
            this.timer = setInterval(() => {
                this.sec = this.sec-1
                this.code_ts = this.sec + 'S后重试'
                this.attcode = false
                if (this.sec === 0) {
                    clearInterval(this.timer)
                    this.sec = 60
                    this.code_ts = this.sec + 'S后重试'
                    this.attcode = true
                }
            }, 1000)
        },
        // 验证码验证成功后，清除定时器
        clearTimer(){
            clearInterval(this.timer)
            this.sec = 60
            this.code_ts = this.sec + 'S后重试'
            this.attcode = true
        },
        reacquireCodeFun(){ // 重新获取验证码
            this.timeCountDown();
            if(this.$route.query.phoneNum){ // 注册时发送手机验证码
                this.$api.registerSendPCode({params:{phone:this.phoneNum}})
                .then(result => {})
            }else{
                if(this.showEmail == 1){ // 登陆时发送手机验证码
                    // 发送验证码
                    this.$api.loginSendCode({params:{phone: this.phoneNum}})
                    .then(result => {})
                }else{ // 注册时发送邮箱验证码
                    this.$api.registerSendECode({params:{email: this.phoneNum}})
                    .then(result => {})
                }
            }
        },

        bindEmail(){// 绑定邮箱
            this.showCodePage = 2
            this.verifiType = 2
            this.placeholderMsgPhone = "输入邮箱"
            this.changeMsg = "切换至手机验证"
            this.phoneNum = ""
            this.bindEmailFlag = 1
            this.uuid = this.$common.guid()
            // 获取图片验证码
            this.getImgCode()
        },
    }
}
</script>

<style lang="scss" scoped>
.verifyPage{
    position: absolute;
    width: 100%;
    height: 100%;
    background-image:url('../../../images/bg003.png');
    background-repeat: no-repeat;
    background-size:100% 100%;
    .backSpan{
        position: absolute;
        right: 20px;
        bottom: 60px;
        font-size: 14px;
        color: #7B3D41;
        cursor: pointer;
    }
    .errMsg{
        display: block;
        margin-left: 15px;
        color: red;
        font-size: 14px;
        line-height: 35px;
    }
    .verify-container{
        width:100%;
        height: 60%;
        .inputBox{
            width: 48%;
            margin-top: 22%;
            margin-left: 30%;
            input{
                width: 100%;
                height: 46px;
                font-size: 18px;
                font-family: 'Microsoft Yahei';
                color: #7B3D41;
                border-radius: 23px;
                background: #fff;
                border:1px solid #78383C;
                &::-webkit-input-placeholder {
                    color: #CCB6B8;
                }
            
            }
            .codeInput{
                display: flex;
                overflow: hidden;
                margin-top: 10px;
                justify-content:space-between;
                align-items: center;
                input{
                    width: 54%; 
                }
                span{
                    display: inline-block;
                    width:40%;
                    cursor: pointer;
                    img{
                        position: relative;
                        // top:15px;
                        // width:90%;
                        height: 50px;
                        margin-left: 30px;
                    }
                }
                
            }
            

        }
        .sendPart{
            width: 48%;
            text-align: center;
            margin:30px auto;
            .sendPhone{
                // width:135px;
                margin-left: 50px;
                font-size: 16px;
                color: #fff;
                background: #7B3D41;
            }
            span.changeSpan{
                color: #7B3D41;
                text-decoration: underline;
                margin-left: 15px;
                cursor: pointer;
            }
        }  
    }
    .verify-send{
      display: flex;
      width:65%;
      height: 50%;
      margin-top: 20%;
      margin-left: 25%;
      background: #fff;
      border:2px solid #7B3D41;
      border-radius: 15px;
      span.text{
        color: #764147;
        font-family: 'Microsoft Yahei';
        font-weight: bold;
        font-size: 20px;
      }
      input.commonBtn{
        height: 41px;
        font-size: 16px;
        font-family: 'Microsoft Yahei';
        color: #fff;
        border-radius: 30px;
        background: #D08B90;
        border:2px solid #fff;
      }
      .content{
          width: 85%;
          height: 80%;
          margin: auto;
          .grayBtn{
            background: #ccc;
          }
          .inputSend{
            text-align: center;
          }
          .codeInput{
              margin-top: 30px;
              
          }
          input{
            &::-webkit-input-placeholder {
              color: #CAB3B4;
            }
          }
          input[type='text']{
            width:50%;
            height: 35px;
            font-size: 16px;
            color: #7B3D41;
            margin-left: 30px;
            color: #CAB3B4;
            margin-left: 15px;
            border-radius: 17px;
            background: #fff;
            border: 1px solid #7B3D41;
          }
          input[type='button']{
            width:30%;
            color: #fff;
            text-indent: 0em;
            text-align: center;
            margin-left: 15px;
            line-height: 35px;
          }
          input.sureBtn{
              line-height: 36px;
              margin:auto;
              background: #7B3D41;
              margin-top: 20px;
          }
      }
      .content-success{
          width: 70%;
          height: 80%;
          margin: auto;
          text-align: center;
          span{
            font-size: 22px;
          }
          .codeInput{
            margin-top:50px;
            input{
                text-indent: 0em;
            }
            .sureBtn{
              width:30%;
              margin-left: 15px;
              &.active{
                background: #78383C;
              }
            }
          }
      }
    }
}
</style>